import React from 'react';
import ReactDOM from 'react-dom';
import { Redirect, withRouter } from 'react-router';
import Login from "../views/Login"
import $axios from "./request"
import store from '@/store'

export function withStorage(...args) {
  return function hoc(InnerComponent) {
    return function OuterComponent(props) {
      let obj = {};
      args.forEach(key => {
        let value = localStorage.getItem(key);
        try { value = JSON.parse(value); } catch { value = value }
        obj[key] = value;
      })
      return <InnerComponent {...obj} {...props}></InnerComponent>
    }
  }
}


// 使用属性代理方式实现用户访问权限控制
export function withLogin(InnerComponent) {
  function OuterComponent(props) {
    console.log("withLogin", props)
    // 判断用户是否登录
    if (props.userInfo?.authorization) {
      // 校验token有效性（是否过期，是否被篡改）
      $axios.get('/api/users/verify').then(({ data: res }) => {
        if (res.code !== 1) {
          props.history.replace({ pathname: '/login', search: 'redirect=' + props.location.pathname })
        }
      })
      return <InnerComponent {...props}></InnerComponent>
    } else {
      return <Redirect to={"/login?redirect=" + props.location.pathname} />
    }
  }
  OuterComponent = withStorage("userInfo")(OuterComponent)
  return withRouter(OuterComponent)
}


// 共享redux所有属性
export function withRedux(InnerComponent) {
  class OuterComponent extends React.Component {
    state = { reduxData: {} }
    componentDidMount() {
      let state = store.getState();
      this.setState({ reduxData: state })
      store.subscribe(() => {
        state = store.getState()
        this.setState({ reduxData: state })
      })
    }
    render() {
      return <InnerComponent {...this.props} {...this.state.reduxData} dispatch={store.dispatch}></InnerComponent>
    }
  }
  return OuterComponent
}

export function withReduxPro(stateCb, dispatchCb) {
  return function hoc(InnerComponent) {
    class OuterComponent extends React.Component {
      state = {
        data: {},
        methods: {},
      }
      getData() {
        const state = store.getState()
        if (typeof stateCb === "function") {
          let data = stateCb(state) || {};
          this.setState({ data })
        }
        let methods = { dispatch: store.dispatch };
        if (typeof dispatchCb === "function") {
          methods = dispatchCb(store.dispatch);
        }
        this.setState({ methods })
      }
      componentDidMount() {
        this.getData()
        store.subscribe(() => this.getData())
      }
      render() {
        let { data, methods } = this.state;
        return <InnerComponent {...this.props} {...data} {...methods}></InnerComponent>
      }
    }
    return OuterComponent
  }
}

export function withAuth(InnerComponent) {
  function OuterComponent(props) {
    console.log("withAuth", props)
    // 判断用户是否登录
    if (props.userInfo?.authorization) {
      // 校验token有效性（是否过期，是否被篡改）
      $axios.get('/api/users/verify').then(({ data: res }) => {
        if (res.code !== 1) {
          props.history.replace({ pathname: '/login', search: 'redirect=' + props.location.pathname })
        }
      })
      return <InnerComponent {...props}></InnerComponent>
    } else {
      return <Redirect to={"/login?redirect=" + props.location.pathname} />
    }
  }
  return withRouter(OuterComponent)
}

export function withUser(InnerComponent) {
  return function OuterComponent(props) {
      let userInfo = localStorage.getItem('userInfo')
      try {
          userInfo = JSON.parse(userInfo) || {}
      } catch (err) {
          userInfo = {}
      }
      return <InnerComponent userInfo={userInfo} {...props}></InnerComponent>
  }
  }



// export function withAuth(InnerComponent) {
//   class OuterComponent extends InnerComponent {
//     componentDidMount() {
//       console.log('withAuth.componentDidMount');
//       super.componentDidMount();
//     }
//     render() {
//       console.log("withAuth", this.props)
//       return (
//         this.props.userInfo?.authorization ?
//           super.render() : <Redirect to="/login" />
//         // <div>只有登录后才能访问</div>
//       )
//     }
//   }
//   return withStorage("userInfo")(OuterComponent);
// }
